/*
 * @Author: WangChenglei wang_chenglei@foxmail.com
 * @Date: 2025-06-09 14:06:12
 * @LastEditors: WangChenglei wang_chenglei@foxmail.com
 * @LastEditTime: 2025-06-09 17:18:53
 * @FilePath: \MDK-ARMd:\RC522\rc522\Src\basetime.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */


#include "basetime.h"


/**
 * BSTIM32 延时基准定时器，代替 SysTick
*/
void DelayTimeBase(void)
{
    FL_BSTIM32_InitTypeDef    defaultInitStruct;

    defaultInitStruct.prescaler = FL_CMU_GetSystemClockFreq()/1000000-1;
    defaultInitStruct.autoReload = 0xffff;
    defaultInitStruct.autoReloadState = FL_ENABLE;
    defaultInitStruct.clockSource = FL_CMU_BSTIM32_CLK_SOURCE_APBCLK;

    FL_BSTIM32_Init(BSTIM32, &defaultInitStruct);
    FL_BSTIM32_Enable(BSTIM32);
}

/**
 * 重定义延时函数，使用 BSTIM32 代替 SysTick
*/
void FL_DelayUs(uint32_t count)
{
    FL_BSTIM32_WriteAutoReload(BSTIM32,count-1);
    FL_BSTIM32_Enable(BSTIM32);
    while(!FL_BSTIM32_IsActiveFlag_Update(BSTIM32))
    {
    }
    FL_BSTIM32_ClearFlag_Update(BSTIM32);
}
/**
 * 重定义延时函数，使用 BSTIM32 代替 SysTick
*/
void FL_DelayUsStart(uint32_t count)
{
    FL_BSTIM32_WriteAutoReload(BSTIM32,count);
    FL_BSTIM32_Enable(BSTIM32);
}

/**
* 重定义延时函数，使用 BSTIM32 代替 SysTick
*/
bool FL_DelayEnd(void)
{
    if(FL_BSTIM32_IsActiveFlag_Update(BSTIM32))
    {
        FL_BSTIM32_ClearFlag_Update(BSTIM32);
        return 1;
    }
    return 0;
}

char RunTimeInfo[400];
uint32_t RunTimeTicks;


void BaseTime(void)
{
    FL_BSTIM16_InitTypeDef    defaultInitStruct;

    defaultInitStruct.prescaler = FL_CMU_GetSystemClockFreq()/1000000-1;;
    defaultInitStruct.autoReload = 1000-1;
    defaultInitStruct.autoReloadState = FL_ENABLE;
    defaultInitStruct.clockSource = FL_CMU_BSTIM16_CLK_SOURCE_APBCLK;
    FL_BSTIM16_Init(BSTIM16, &defaultInitStruct);

    FL_BSTIM16_ClearFlag_Update(BSTIM16);
    FL_BSTIM16_EnableIT_Update(BSTIM16);

    /*NVIC中断配置*/
    NVIC_DisableIRQ(BSTIM_IRQn);
    NVIC_SetPriority(BSTIM_IRQn, 2); //中断优先级配置
    NVIC_EnableIRQ(BSTIM_IRQn);

    FL_BSTIM16_Enable(BSTIM16);
}



void BSTIM_IRQHandler()
{
    if(FL_BSTIM16_IsEnabledIT_Update(BSTIM16) && FL_BSTIM16_IsActiveFlag_Update(BSTIM16))
    {
        FL_BSTIM16_ClearFlag_Update(BSTIM16);
        RunTimeTicks++;

    }

}


uint32_t millis()
{
    return RunTimeTicks;
}
